package xyz.hubery.vo;

import lombok.Data;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import xyz.hubery.geetest.GeetestLib;
import xyz.hubery.geetest.entity.GeetestLibResult;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 极验验证表单
 */
@Data
public class GeetestCheckForm {

    /**
     * 极验验证
     */
    private String geetest_challenge;
    private String geetest_seccode;
    private String geetest_validate;
    private String uuid;

    public void check(GeetestCheckForm geetestCheckForm, GeetestLib geetestLib, RedisTemplate<String,String> redisTemplate){
        String challenge = geetestCheckForm.getGeetest_challenge();
        String validate = geetestCheckForm.getGeetest_validate();
        String seccode = geetestCheckForm.getGeetest_seccode();
        int status = 0;
        String userId = "";
        // session 必须取出值，若取不出值，直接当做异常退出
        String statusStr =
                redisTemplate.opsForValue().get(GeetestLib.GEETEST_SERVER_STATUS_SESSION_KEY+":"+geetestCheckForm.getUuid()).toString();
        status = Integer.parseInt(statusStr);
        userId = redisTemplate.opsForValue().get(GeetestLib.GEETEST_SERVER_USER_KEY + ":" +
                geetestCheckForm.getUuid()).toString();

        GeetestLibResult result = null;
        if (status == 1) {
            /*自定义参数,可选择添加
            user_id 客户端用户的唯一标识，确定用户的唯一性；作用于提供进阶数据分析服务，可在 register 和 validate 接口传入，不传入也不影响验证服务的使用；若担心用户信息风险，可作预处理(如哈希处理)再提供到极
            验
            client_type 客户端类型，web：电脑上的浏览器；h5：手机上的浏览器，包括移动应用内完全内置
            的 web_view；native：通过原生 sdk 植入 app 应用的方式；unknown：未知
            ip_address 客户端请求 sdk 服务器的 ip 地址
            */
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("user_id", userId);
            paramMap.put("client_type", "web");
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
            String ip = request.getRemoteAddr();
            paramMap.put("ip_address", ip);
            result = geetestLib.successValidate(challenge, validate, seccode, paramMap);
        } else {
            result = geetestLib.failValidate(challenge, validate, seccode);
        }
        if(result.getStatus()!=1){
            throw new IllegalArgumentException("验证码验证异常") ;
        }
    }
}
